﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using OdsServer.Common.DataTransfer;

namespace OdsServer.Common.Utils
{
    public static class DataTransferUtils
    {
        public static IPAddress GetMachineIP()
        {
            String hostName     = Dns.GetHostName();
            IPHostEntry ipEntry = Dns.GetHostEntry(hostName);
            IPAddress[] addr    = ipEntry.AddressList;
            IPAddress ipv4      = null;

            foreach (IPAddress item in addr)
            {
                if (item.AddressFamily == AddressFamily.InterNetwork)
                {
                    ipv4 = item;
                    break;
                }
            }
            if (ipv4 == null)
            {
                throw new DataTransferException("No IPv4 address associated. Server can not run witout it");
            }
            return ipv4;
        }

        public static byte[] RawSerialize(object anything)
        {
            int rawsize     = Marshal.SizeOf(anything);
            byte[] rawdata  = new byte[rawsize];
            GCHandle handle = GCHandle.Alloc(rawdata, GCHandleType.Pinned);

            Marshal.StructureToPtr(
                    anything,
                    handle.AddrOfPinnedObject(),
                    false );

            handle.Free();

            return rawdata;
        }

        public static T RawDeserialize<T>(byte[] rawdatas)
        {
            int rawsize     = Marshal.SizeOf(typeof(T));
            IntPtr buffer   = Marshal.AllocHGlobal(rawsize);

            Marshal.Copy(rawdatas, 0, buffer, rawsize);
            T retobj = (T)Marshal.PtrToStructure(buffer, typeof(T));
            Marshal.FreeHGlobal(buffer);

            return retobj;
        }
    }
}